package com.lagou.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.sql.rowset.CachedRowSet;

import com.lagou.dao.ForumDao;
import com.lagou.entity.Forum;
import com.lagou.util.JDBCUtil2;

public class ForumDaoImpl implements ForumDao{
JDBCUtil2 util=JDBCUtil2.getInit();
	@Override
	public List<Forum> queryAll() {
		List<Forum> list=new ArrayList<Forum>();
		CachedRowSet rs=util.query("\r\n" + 
				"SELECT fid,fname,ftext,ftime,DATE_FORMAT(ftime,'%Y-%m-%d %H:%i:%s')mytime from forum order by ftime desc ");
		try {
			while(rs.next()) {
				Forum c=new Forum(rs.getInt("fid"),rs.getString("fname"),rs.getString("ftext"),rs.getString("mytime"));
				list.add(c);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			util.closeCacheRowSet(rs);
		}
		return list;
	}
	@Override
	public int getCount() {
		String sql="select count(fid) mycount from forum";
		CachedRowSet rs=util.query(sql);
		try {
			if(rs.next()) {
				return rs.getInt("mycount");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			util.closeCacheRowSet(rs);
		}
		return -1;
	}
	@Override
	public List<Forum> queryByPage(int page, int size) {
		List<Forum> list=new ArrayList<Forum>();
		CachedRowSet rs=util.query("\r\n" + 
				"SELECT fid,fname,ftext,ftime,DATE_FORMAT(ftime,'%Y-%m-%d %H:%i:%s')mytime from forum order by ftime desc limit "+(page-1)*size+" , "+size);
		try {
			while(rs.next()) {
				Forum c=new Forum(rs.getInt("fid"),rs.getString("fname"),rs.getString("ftext"),rs.getString("mytime"));
				list.add(c);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			util.closeCacheRowSet(rs);
		}
		return list;
	}
	@Override
	public boolean qureryAdd(String fname, String ftext) {
		boolean update = util.update("INSERT into forum(fname, ftext) value(?,?) ",fname, ftext);
		return update;
	}
	@Override
	public boolean deleteforum(int fid) {
		boolean update = util.update("delete  from forum where fid=? ",fid);
		return update;
	}

}
